package com.myproject.weather.broadcastReceiver;

import com.myproject.weather.weatherInfo.WeatherSession;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.util.Log;

public class UpdateWeatherService extends BroadcastReceiver {
	private Context mContext;

	@Override
	public void onReceive(Context context, Intent intent) {
		this.mContext = context;
		String str = intent.getAction();
		if ("android.net.conn.CONNECTIVITY_CHANGE".equals(str)) {
			if (intent.getBooleanExtra("noConnectivity", false)) {
				stopUpdate(mContext);
			} else {
				startUpdate(mContext, false);
				update();
			}
		} else {
			update();
		}
	}

	private void update() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				WeatherSession session = new WeatherSession(mContext);
				try {
					session.updateWeather();
				} catch (Exception e) {
				}
			}
		}).start();
	}

	public static void startUpdate(Context paramContext, boolean paramBoolean) {
		AlarmManager localAlarmManager = (AlarmManager) paramContext.getSystemService("alarm");
		Intent localIntent = new Intent(paramContext, UpdateWeatherService.class);
		PendingIntent localPendingIntent = PendingIntent.getBroadcast(paramContext, 0, localIntent,
				PendingIntent.FLAG_CANCEL_CURRENT);
		if (paramBoolean) {
			paramContext.sendBroadcast(localIntent);
		}
		localAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME,
				1000 * 60 * 15 + SystemClock.elapsedRealtime(), 1000 * 60 * 15, localPendingIntent);
	}

	public static void stopUpdate(Context paramContext) {
		((AlarmManager) paramContext.getSystemService("alarm")).cancel(PendingIntent.getBroadcast(
				paramContext, 0, new Intent(paramContext, UpdateWeatherService.class),
				PendingIntent.FLAG_CANCEL_CURRENT));
	}
}
